import styles from './style.module.scss'
import { Outlet, useLoaderData, useNavigate } from 'react-router-dom'
import React, { useEffect, useState } from 'react'
import SplitPane from 'react-split-pane'
import { ContextMenu, MenuItem, ContextMenuTrigger } from 'react-contextmenu'
import { Add, Delete, Redo } from '@icon-park/react'
import { Input } from 'antd'

export default function ConfigPage() {
  const list: CategoryType[] = useLoaderData()
  const [categories, setCategories] = useState<CategoryType[]>([])
  const [id, setId] = useState(-1)
  const [search, setSearch] = useState('')
  const navigate = useNavigate()

  useEffect(() => {
    setCategories(list)
    if (list.length > 0) {
      setId(list[0].id)
      navigate(`/config/contentList/${list[0].id}`, { replace: true })
    } else {
      navigate(`/config/contentList`, { replace: true })
    }
  }, [list])

  const updateCategories = async () => {
    const newList: CategoryType[] = await window.api.sql(
      `SELECT *
       FROM categories order by id desc `,
      'findAll'
    )
    setCategories(newList)
  }

  const handleDelete = async (id: number) => {
    await Promise.all([
      window.api.sql(
        `DELETE
         FROM categories
         WHERE id = ${id}`,
        'del'
      ),
      window.api.sql(
        `DELETE
         FROM contents
         WHERE category_id = @category_id`,
        'del',
        { category_id: id }
      )
    ])
    updateCategories()
    navigate(`/config/contentList/${categories[0]?.id || ''}`, { replace: true })
  }

  const handleRename = (id: number) => {
    setCategories((prevCategories) =>
      prevCategories.map((item) => (item.id === id ? { ...item, isEdit: true } : item))
    )
  }

  const handleBlur = async (e: any, id: number) => {
    const newName = e.target.value
    await window.api.sql(
      `UPDATE categories
       SET name = '${newName}'
       WHERE id = ${id}`,
      'update'
    )
    updateCategories()
  }

  const handleAdd = async () => {
    await window.api.sql(
      `INSERT INTO categories (name, created_at)
       VALUES ('未命名分类', datetime())`,
      'insert'
    )
    updateCategories()
  }

  const handleSearch = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const searchWord = e.target.value.trim()
    setSearch(searchWord)

    const query = searchWord
      ? `SELECT *
         FROM categories
         WHERE name LIKE @searchWord`
      : `SELECT *
         FROM categories`

    const params = searchWord ? { searchWord: `%${searchWord}%` } : undefined
    const newList: CategoryType[] = await window.api.sql(query, 'findAll', params)
    setCategories(newList)
  }

  const renderCategoryItem = (item: CategoryType) => (
    <div key={item.id}>
      {item.isEdit ? (
        <Input
          onKeyDown={(e: React.KeyboardEvent<HTMLInputElement>) =>
            e.key === 'Enter' && handleBlur(e, item.id)
          }
          onBlur={(e) => handleBlur(e, item.id)}
          defaultValue={item.name}
          style={{ height: '40px', boxShadow: 'none' }}
        />
      ) : (
        // @ts-ignore
        <ContextMenuTrigger
          id={`unique_${item.id}`}
          attributes={{
            className: `${item.id === id ? styles.active : ''} ${styles.item} u-line-1`
          }}
        >
          <div
            onClick={() => {
              if (id !== item.id) {
                setId(item.id)
                navigate(`/config/contentList/${item.id}`)
              }
            }}
          >
            {item.name}
          </div>
        </ContextMenuTrigger>
      )}
      {/* @ts-ignore*/}
      <ContextMenu
        id={`unique_${item.id}`}
        hideOnLeave={true}
        className={`py-[10px] box-border ${styles.contextMenu}`}
      >
        {/* @ts-ignore*/}
        <MenuItem onClick={() => handleRename(item.id)} className={styles.contextMenuItem}>
          <Redo theme="outline" size="16" fill="#333" style={{ marginRight: '9px' }} />
          重命名
        </MenuItem>
        {/* @ts-ignore*/}
        <MenuItem onClick={() => handleDelete(item.id)} className={styles.contextMenuItem}>
          <Delete theme="outline" size="16" fill="#333" style={{ marginRight: '9px' }} />
          删除
        </MenuItem>
      </ContextMenu>
    </div>
  )

  return (
    <div className={styles.container}>
      {/* @ts-ignore*/}
      <SplitPane split="vertical" minSize={150} defaultSize={200} maxSize={300}>
        <div className={styles.left}>
          <div className={styles.category}>{categories.map(renderCategoryItem)}</div>
          <div className={styles.nav}>
            <Add theme="outline" size="20" fill="#333" onClick={handleAdd} />
            <input className="border ml-2 flex-1 w-full" onChange={handleSearch} value={search} />
          </div>
        </div>
        <div className={styles.content}>
          <Outlet />
        </div>
      </SplitPane>
    </div>
  )
}
